package org.jeecg.modules.wlhy.order.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ExcelUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.hycarrier.entity.HyCarrier;
import org.jeecg.modules.wlhy.hycarrier.service.IHyCarrierService;
import org.jeecg.modules.wlhy.hycarrier.service.IHyZhenCarrierOrderDriverService;
import org.jeecg.modules.wlhy.hyproject.service.IHyProjectService;
import org.jeecg.modules.wlhy.hyzhencarrier.service.IHyZhenCarrierService;
import org.jeecg.modules.wlhy.order.entity.*;
import org.jeecg.modules.wlhy.order.service.IHyOrderReceiveAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderSendAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.order.vo.HyOrderVO;
import org.jeecg.modules.wlhy.shipping.controller.HttpURLConnectionUtil;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: hy_order
 * @Author: jeecg-boot
 * @Date:   2020-12-03
 * @Version: V1.0
 */
@Api(tags="hy_order")
@RestController
@RequestMapping("/order/hyOrder")
//@RequiresRoles(value={"admin", "customer", "driver"},logical = Logical.OR)
@Slf4j
public class HyOrderController extends JeecgController<HyOrder, IHyOrderService> {
	@Autowired
	private IHyOrderService hyOrderService;

	@Autowired
	private IHyCarrierService hyCarrierService;

	@Autowired
	private UserUtil userUtil;
	@Autowired private IHyOrderSendAddressService hyOrderSendAddressService;
	@Autowired private IHyOrderReceiveAddressService hyOrderReceiveAddressService;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;

	@Autowired
	private IHyCustomerService customerService;

	@Autowired
	private IHyProjectService hyProjectService;

	@Autowired
	private IHyZhenCarrierOrderDriverService hyZhenCarrierOrderDriverService;

	@Autowired
	private IHyZhenCarrierService hyZhenCarrierService;
	@Autowired
	private IHyCaptainService hyCaptainService;
	@Autowired
	private IHyShippingNoteService hyShippingNoteService;

	private void setQueryWrapper(HyOrder hyOrder,QueryWrapper<HyOrderVO> queryWrapper){
		if(StringUtils.isNotEmpty(hyOrder.getOrderNum())){
			queryWrapper.like("hy_order.order_num",hyOrder.getOrderNum());
		}

		if(StringUtils.isNotBlank(hyOrder.getCustomerId())){
			queryWrapper.eq("hy_order.customer_id",hyOrder.getCustomerId());
		}

		if(StringUtils.isNotEmpty(hyOrder.getOrderStatus())){
			queryWrapper.in("hy_order.order_status",Arrays.asList(hyOrder.getOrderStatus().split(",")));
		}

		if(StringUtils.isNotEmpty(hyOrder.getOrderType())){
			queryWrapper.eq("hy_order.order_type",hyOrder.getOrderType());
		}
		if(StringUtils.isNotEmpty(hyOrder.getPayType())){
			queryWrapper.eq("hy_order.pay_type",hyOrder.getPayType());
		}

		if(StringUtils.isNotEmpty(hyOrder.getOrderMode())){
			queryWrapper.eq("hy_order.order_mode",hyOrder.getOrderMode());
		}

		if(StringUtils.isNotEmpty(hyOrder.getCarrierId())){
			queryWrapper.eq("hy_order.carrier_id",hyOrder.getCarrierId());
		}
		if(StringUtils.isNotEmpty(hyOrder.getAddressSendId())){
			queryWrapper.eq("hy_order.address_send_id",hyOrder.getAddressSendId());
		}
		if(StringUtils.isNotEmpty(hyOrder.getAddressReceiveId())){
			queryWrapper.eq("hy_order.address_receive_id",hyOrder.getAddressReceiveId());
		}

		if(StringUtils.isNotEmpty(hyOrder.getDescriptionOfGoods())){
			queryWrapper.like("hy_order.description_of_goods",hyOrder.getDescriptionOfGoods());
		}

		if(StringUtils.isNotEmpty(hyOrder.getCreateBy())){
			queryWrapper.eq("hy_order.create_by",hyOrder.getCreateBy());
		}

		if(StringUtils.isNotEmpty(hyOrder.getKhdh())){
			queryWrapper.like("hy_order.khdh",hyOrder.getKhdh());
		}
		if(StringUtils.isNotEmpty(hyOrder.getIntroducer())){
			queryWrapper.like("hy_order.introducer",hyOrder.getIntroducer());
		}
		if(StringUtils.isNotEmpty(hyOrder.getDispatcher())){
			queryWrapper.like("hy_order.dispatcher",hyOrder.getDispatcher());
		}

	}

	@ApiOperation(value="hy_order-分页列表查询", notes="hy_order-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyOrder hyOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyOrderVO> queryWrapper = new QueryWrapper<>();

		HyCustomer customer = userUtil.getCustomer();
		if(customer!=null){
			hyOrder.setCustomerId(null);
			queryWrapper.eq("hy_order.customer_id",customer.getId());
		}
		SysUser user = userUtil.getUser();
		if (UserTypeEnum.业务管理员.getCode().equals(user.getUType())) {
			queryWrapper.in("hy_order.customer_id", userUtil.getCustomerAdminRelationIdList());
		}

//		if(UserTypeEnum.承运商.getCode().equals(user.getUType())){
//			HyZhenCarrier zhenCarrier = hyZhenCarrierService.getOne(new QueryWrapper<HyZhenCarrier>()
//			.eq("user_id",user.getId())
//			);
//			if(zhenCarrier!=null){
//				List<String> orderIdListByCarrierId = hyZhenCarrierOrderDriverService.getOrderIdListByCarrierId(zhenCarrier.getId());
//				if(CollectionUtils.isNotEmpty(orderIdListByCarrierId) ){
//					queryWrapper.in("hy_order.id" ,orderIdListByCarrierId);
//				}else{
//					return Result.OK();
//				}
//			}
//		}
		if (UserTypeEnum.承运商.getCode().equals(user.getUType())) {
			HyCaptain hyCaptain = hyCaptainService.getInfoByUserId(user.getId());
			if (hyCaptain!=null) {
				queryWrapper.eq("hy_order_captain.captain_id",hyCaptain.getId());
			}
			setQueryWrapper(hyOrder,queryWrapper);
			String dtPublish_begin = req.getParameter("dtPublish_begin");
			if(StringUtils.isNotEmpty(dtPublish_begin)){
				queryWrapper.ge("hy_order.dt_Publish",dtPublish_begin);
			}
			String dtPublish_end = req.getParameter("dtPublish_end");
			if(StringUtils.isNotEmpty(dtPublish_end)){
				queryWrapper.le("hy_order.dt_Publish",dtPublish_end);
			}

			queryWrapper.eq("hy_order.del_flag","0");
			queryWrapper.groupBy("hy_order.id");
			queryWrapper.orderByDesc("hy_order.create_time");
			queryWrapper.orderByDesc("hy_order.dt_publish");

			Page<HyOrderVO> page = new Page<HyOrderVO>(pageNo, pageSize);
			IPage<HyOrderVO> pageList = hyOrderService.getPageListByCaptaionId(page, queryWrapper);
			for (HyOrderVO dto : pageList.getRecords()) {
				dto.setCarrierUnitFee(dto.getCaptainFee());
				dto.setShippingNums(new BigDecimal(hyShippingNoteService.list(new QueryWrapper<HyShippingNote>().eq("order_id",dto.getId()).eq("captain_id",hyCaptain.getId())).size()));
			}
			return Result.OK(pageList);

		}
		setQueryWrapper(hyOrder,queryWrapper);

		String dtPublish_begin = req.getParameter("dtPublish_begin");
		if(StringUtils.isNotEmpty(dtPublish_begin)){
			queryWrapper.ge("hy_order.dt_Publish",dtPublish_begin);
		}
		String dtPublish_end = req.getParameter("dtPublish_end");
		if(StringUtils.isNotEmpty(dtPublish_end)){
			queryWrapper.le("hy_order.dt_Publish",dtPublish_end);
		}

		queryWrapper.eq("hy_order.del_flag","0");
		queryWrapper.groupBy("hy_order.id");
		queryWrapper.orderByDesc("hy_order.create_time");
		queryWrapper.orderByDesc("hy_order.dt_publish");

		Page<HyOrderVO> page = new Page<HyOrderVO>(pageNo, pageSize);
		IPage<HyOrderVO> pageList = hyOrderService.getPageList(page, queryWrapper);
		return Result.OK(pageList);
	}

	@ApiOperation(value="hy_order-代理货源分页列表查询", notes="hy_order-代理货源分页列表查询")
	@GetMapping(value = "/agentlist")
	public Result<?> getAgentList(HyOrder hyOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<HyOrderVO> queryWrapper = new QueryWrapper<>();
		HyCustomer customer = userUtil.getCustomer();
		if(customer!=null){
//			hyOrder.setCustomerId(null);
			hyOrder.setAgentId(null);
			queryWrapper.eq("hy_order.agent_id",customer.getId());
		}

		SysUser user = userUtil.getUser();
		if (UserTypeEnum.业务管理员.getCode().equals(user.getUType())) {
			queryWrapper.in("hy_order.customer_id", userUtil.getCustomerAdminRelationIdList());
		}

		setQueryWrapper(hyOrder,queryWrapper);

		String dtPublish_begin = req.getParameter("dtPublish_begin");
		if(StringUtils.isNotEmpty(dtPublish_begin)){
			queryWrapper.ge("hy_order.dt_Publish",dtPublish_begin);
		}
		String dtPublish_end = req.getParameter("dtPublish_end");
		if(StringUtils.isNotEmpty(dtPublish_end)){
			queryWrapper.le("hy_order.dt_Publish",dtPublish_end);
		}
		if(StringUtils.isNotEmpty(hyOrder.getKeyword())){
			queryWrapper.and(
					qw -> qw.like("hy_order.send_address_name", hyOrder.getKeyword())
							.or().like("hy_order.receive_address_name", hyOrder.getKeyword())
			);
		}

		queryWrapper.eq("hy_order.del_flag","0");
		queryWrapper.groupBy("hy_order.id");
		queryWrapper.orderByDesc("hy_order.create_time");
		queryWrapper.orderByDesc("hy_order.dt_publish");

		Page<HyOrderVO> page = new Page<HyOrderVO>(pageNo, pageSize);
		IPage<HyOrderVO> pageList = hyOrderService.getPageList(page, queryWrapper);
		return Result.OK(pageList);
	}



	 @GetMapping(value = "/all")
	 public Result<?> getAll(HyOrder hyOrder,HttpServletRequest req) {
		 QueryWrapper<HyOrder> queryWrapper = QueryGenerator.initQueryWrapper(hyOrder, req.getParameterMap());
		 String keyword = req.getParameter("keyword");
		 if (StringUtils.isNotEmpty(keyword)) {
		/*	 Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
			 Matcher m = p.matcher(keyword);
			 if (m.find()) {
				 queryWrapper.and(qw->{
					 qw.like("send_address_name", keyword)
					 .or()
					 .like("receive_address_name", keyword);
				 });

			 }else{
				 queryWrapper.like("order_num", keyword);
			 }*/
			 queryWrapper.and(qw->{
				 		  qw.like("order_num", keyword)
						 .or()
						 .like("send_address_name", keyword)
						 .or()
						 .like("receive_address_name", keyword);
			 });
		 }
		 if (userUtil.isSys()) {
			 String cid = req.getParameter("cid");
			 if (StringUtils.isEmpty(cid)) {
				 return Result.error("未获取到数据");
			 }
			 queryWrapper.eq("customer_id", cid);
		 } else {
			 HyCustomer customer = userUtil.getCustomer();
			 if(customer == null){
				return Result.error("未获取到数据");
			 }
			 queryWrapper.eq("customer_id", customer.getId());
		 }
		 List<HyOrder> list = hyOrderService.list(queryWrapper);
		 return Result.OK(list);
	 }


	@AutoLog(value = "hy_order-添加")
	@ApiOperation(value="hy_order-添加", notes="hy_order-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("hyorder:add")
	public Result<?> add(@RequestBody HyOrderDTO hyOrder) {
		return hyOrderService.addOrder(hyOrder);
	}

	@AutoLog(value = "hy_order-添加差价货源")
	@ApiOperation(value="hy_order-添加差价货源", notes="hy_order-添加差价货源")
	@PostMapping(value = "/addAgentOrder")
	@RequiresPermissions("hyorder:add")
	public Result<?> addAgentOrder(@RequestBody HyOrderDTO hyOrder) {
		return hyOrderService.addAgentOrder(hyOrder);
	}

	/**
	 *  编辑
	 *
	 * @param hyOrder
	 * @return
	 */
	@AutoLog(value = "hy_order-编辑")
	@ApiOperation(value="hy_order-编辑", notes="hy_order-编辑")
	@PutMapping(value = "/edit")
	@RequiresPermissions("hyorder:edit")
	public Result<?> edit(@RequestBody HyOrderDTO hyOrder) {
		return hyOrderService.editOrder(hyOrder);
	}

	/**
	 *  获取货源收发货地址
	 *
	 * @param orderId
	 * @return
	 */
	@GetMapping(value = "/getAddressByOrderId")
	public Result<?> getAddressByOrderId( @RequestParam(name="orderId") String orderId) {
		List<HyOrderSendAddress> sendList = hyOrderSendAddressService.getListByOrderId(orderId);
		List<HyOrderReceiveAddress> receiveList = hyOrderReceiveAddressService.getListByOrderId(orderId);
		Map map =new HashMap();
		map.put("sendList",sendList);
		map.put("receiveList",receiveList);
		Result result=new Result();
		result.setResult(map);
		return result;
	}

//	 @AutoLog(value = "hy_order-调价")
//	 @ApiOperation(value="hy_order-调价", notes="hy_order-调价")
//	 @PutMapping(value = "/tiaojia")
//	 @RequiresPermissions("hyorder:tiaojia")
//	 @Transactional
//	 public Result<?> tiaojia(@RequestBody HyOrder hyOrder) {
//
//		 String id = hyOrder.getId();
//		 HyOrder  order = hyOrderService.getById(id);
//		 if(order==null){
//			 return Result.error("货源信息不存在!");
//		 }
//		 //加入调价历史记录-----------------
//		 hyPriceHistoryService.setPriceHistory(order);
//
//		 HyCustomer customer = null;
//		 if(userUtil.isSys()){
//			 String customerId = order.getCustomerId();
//			 if(StringUtils.isEmpty(customerId)){
//				 return Result.error("货主信息不存在");
//			 }
//			 customer = userUtil.getCustomerById(customerId);
//		 }else {
//			 customer = userUtil.getCustomer();
//		 }
//		 if(customer == null){
//			 return Result.error("货主信息不存在");
//		 }
//
//		 if(!StringUtils.equals(order.getCustomerId(),customer.getId())){
//			 return Result.error("货源信息错误!");
//		 }
//		 HyCustomerCompany customerCompany = userUtil.getCustomerCompany(customer.getId());
//		 BigDecimal costServicePercent = customerCompany.getCostServicePercent();
//		 if(costServicePercent == null){
//			 return Result.error("公司服务信息错误");
//		 }
//		 BigDecimal goodsWeight = order.getGoodsWeight();
//		 BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
//		 //账期计算
//		 String shippingType = hyOrder.getShippingType();
//		 BigDecimal yf;
//		 if("1".equals(shippingType)){
//			 yf = goodsWeight.multiply(shippingUnitPrice);
//		 }else if("4".equals(shippingType)){
//			 yf = shippingUnitPrice;
//		 }else {
//			 return Result.error("运费计算方式错误");
//		 }
//		 //账期金额
////		 BigDecimal server = yf.multiply(costServicePercent);
////		 BigDecimal accPeriod = yf.add(server);  //.setScale(2, BigDecimal.ROUND_HALF_UP);
////		 order.setAccPeriodAmt(accPeriod);
//
//		 order.setShippingType(shippingType);
//		 order.setShippingUnitPrice(shippingUnitPrice);
//		 order.setLossGoodsUnitPrice(hyOrder.getLossGoodsUnitPrice());
//		 order.setLossType(hyOrder.getLossType());
//		 order.setLossProportion(hyOrder.getLossProportion());
//		 String izUsedGas = hyOrder.getIzUsedGas();
//		 //验证油气费,不能大于费用的30%
//		 if("1".equals(izUsedGas)){
//			 HyCompanyConfig companyConfig = hyCompanyConfigService.getByCompanyId(customerCompany.getCompanyId());
//			 if(companyConfig == null){
//				 return Result.error("未找到公司配置信息!");
//			 }
//			 if(!companyConfig.getIzGasUsed()){
//				 return Result.error("签约公司不支持油气!");
//			 }
//
//			 HyConfig gasConfig = hyConfigService.getByTag("gas");
//			 if(gasConfig == null){
//				 return Result.error("未找到油气配置信息!");
//			 }
//			 if(!gasConfig.getIzUse()){
//				 return Result.error("油气功能已关闭!");
//			 }
//
//			 BigDecimal gasRechargeAmount = hyOrder.getGasRechargeAmount();
//			 if(gasRechargeAmount == null){
//				 return Result.error("油气充值金额不正确");
//			 }
//
//			 BigDecimal yqf = yf.multiply(new BigDecimal("0.3"));
//			 if(gasRechargeAmount.compareTo(yqf) == 1){
//				 return Result.error("油气充值金额不能大于运费的30%");
//			 }
//			 order.setIzUsedGas("1");
//			 order.setGasRechargeAmount(gasRechargeAmount);
//		 }else {
//			 order.setIzUsedGas("0");
//			 order.setGasRechargeAmount(BigDecimal.ZERO);
//		 }
//
//		 hyOrderService.updateById(order);
//		 return Result.OK("调价成功!");
//	 }

	 @AutoLog(value = "货源-发布")
	 @ApiOperation(value="货源-发布", notes="货源-发布")
	 @PutMapping(value = "/publish")
	 @RequiresPermissions("hyorder:publish")
	 public Result<?> publish(@RequestParam(name="id",required=true) String id) {

		 if(StringUtils.isEmpty(id)){
			 return Result.error("id不能为空");
		 }
		 HyOrder hyOrder = hyOrderService.getById(id);
		 if(hyOrder == null){
			 return Result.error("货源信息不存在");
		 }
		 HyCustomer customer = null;
		 if(userUtil.isSys()){
			 String customerId = hyOrder.getCustomerId();
			 if(StringUtils.isEmpty(customerId)){
				 return Result.error("货主信息不存在");
			 }
			 customer = userUtil.getCustomerById(customerId);
			 if(customer == null){
				 return Result.error("货主信息不存在");
			 }
		 }else {
			 customer = userUtil.getCustomer();
		 }
		 if(customer == null){
			 return Result.error("货主信息不存在");
		 }
		 //判断货主在货主模式下不能发布
		 if (userUtil.getLoginUser().getUType().equals("2")||userUtil.getLoginUser().getUType().equals("3")){
		 	if (hyOrder.getOrderMode().equals("4")){
		 		return Result.error("货主在货主模式下不能进行发布");
			 }
		 }

		 if (StrUtil.isEmpty(hyOrder.getCostServiceId())) {
			return Result.error("服务费比例不存在，请在[货源列表]中添加服务费比例");
		 }

		 BigDecimal shippingUnitPrice = hyOrder.getShippingUnitPrice();
		 if(shippingUnitPrice == null || shippingUnitPrice.compareTo(BigDecimal.ZERO)==0){
			 return Result.error("运费单价不能为空");
		 }

		 String orderMode = hyOrder.getOrderMode();
		 if("3".equals(orderMode)){
			 if (!StringUtils.equals(hyOrder.getAgentId(), customer.getId())
					 && !StringUtils.equals(hyOrder.getCustomerId(), customer.getId())
			 ) {
				 return Result.error("货源信息错误!");
			 }
			 //检查是否可以发布
			 if(StringUtils.isEmpty(hyOrder.getAgentId())){
				 return Result.error("经纪人不能为空");
			 }
			 BigDecimal agentPrice = hyOrder.getAgentPrice();
			 if(agentPrice == null){
				 return Result.error("经纪人运费不能为空");
			 }
		 }else {
			 if(!StringUtils.equals(hyOrder.getCustomerId(),customer.getId())){
				 return Result.error("货源信息错误!");
			 }
		 }

		 hyOrder.setOrderStatus("2");
		 hyOrder.setDtPublish(new Date());//货源发布日期
		 hyOrderService.updateById(hyOrder);
		 return Result.OK("发布成功!");
	 }


	 @AutoLog(value = "货源-完结")
	 @ApiOperation(value="货源-完结", notes="货源-完结")
	 @PutMapping(value = "/finish")
	 @RequiresPermissions("hyorder:finish")
	 public Result<?> finish(@RequestBody HyOrder hyOrder) {
		 String id = hyOrder.getId();
		 if(StringUtils.isEmpty(id)){
			 return Result.error("id不能为空");
		 }
		 HyOrder oldorder = hyOrderService.getById(id);
		 if(oldorder == null){
			 return Result.error("货源信息不存在");
		 }
		 HyCustomer customer = null;
		 if(userUtil.isSys()){
			 String customerId = oldorder.getCustomerId();
			 if(StringUtils.isEmpty(customerId)){
				 return Result.error("货主信息不存在");
			 }
			 customer = userUtil.getCustomerById(customerId);
			 if(customer == null){
				 return Result.error("货主信息不存在");
			 }
		 }else {
			 customer = userUtil.getCustomer();
		 }
		 if(customer == null){
			 return Result.error("货主信息不存在");
		 }
		 if("3".equals(hyOrder.getOrderMode())){
			 if (!StringUtils.equals(hyOrder.getAgentId(), customer.getId())
					 && !StringUtils.equals(hyOrder.getCustomerId(), customer.getId())
			 ) {
				 return Result.error("货源信息错误!");
			 }
		 }else {
			 if(!StringUtils.equals(hyOrder.getCustomerId(),customer.getId())){
				 return Result.error("货源信息错误!");
			 }
		 }

		 oldorder.setOrderStatus("8");
		 oldorder.setDtFinish(new Date());//货源完结日期
		 hyOrderService.updateById(oldorder);
		 return Result.OK("操作成功!");
	 }

	@ApiOperation(value="货源-恢复", notes="货源-恢复")
	@PutMapping(value = "/reuse")
	@RequiresPermissions("hyorder:finish")
	public Result<?> reuse(@RequestBody HyOrder hyOrder) {
		String id = hyOrder.getId();
		if(StringUtils.isEmpty(id)){
			return Result.error("id不能为空");
		}
		HyOrder oldorder = hyOrderService.getById(id);
		if(oldorder == null){
			return Result.error("货源信息不存在");
		}
		HyCustomer customer = null;
		if(userUtil.isSys()){
			String customerId = oldorder.getCustomerId();
			if(StringUtils.isEmpty(customerId)){
				return Result.error("货主信息不存在");
			}
			customer = userUtil.getCustomerById(customerId);
			if(customer == null){
				return Result.error("货主信息不存在");
			}
		}else {
			customer = userUtil.getCustomer();
		}
		if(customer == null){
			return Result.error("货主信息不存在");
		}

		if("3".equals(hyOrder.getOrderMode())){
			if (!StringUtils.equals(hyOrder.getAgentId(), customer.getId())
					&& !StringUtils.equals(hyOrder.getCustomerId(), customer.getId())
			) {
				return Result.error("货源信息错误!");
			}
		}else {
			if(!StringUtils.equals(hyOrder.getCustomerId(),customer.getId())){
				return Result.error("货源信息错误!");
			}
		}
		oldorder.setOrderStatus("2");
//		oldorder.setDtFinish(new Date());//货源完结日期
		hyOrderService.updateById(oldorder);
		return Result.OK("操作成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "hy_order-通过id删除")
	@ApiOperation(value="hy_order-通过id删除", notes="hy_order-通过id删除")
	@DeleteMapping(value = "/delete")
	@RequiresPermissions("hyorder:delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		if(StringUtils.isEmpty(id)){
			return Result.error("id不能为空");
		}
		HyOrder oldorder = hyOrderService.getById(id);
		if(oldorder == null){
			return Result.error("货源信息不存在");
		}
		int shippingNums = hyOrderService.getShippingNums(id);
		if(shippingNums > 0){
			return Result.error("该货源已接单,不能删除");
		}

		HyCustomer customer = null;
		if(userUtil.isSys()){
			String customerId = oldorder.getCustomerId();
			if(StringUtils.isEmpty(customerId)){
				return Result.error("货主信息不存在");
			}
			customer = userUtil.getCustomerById(customerId);
			if(customer == null){
				return Result.error("货主信息不存在");
			}
		}else {
			customer = userUtil.getCustomer();
		}
		if(customer == null){
			return Result.error("货主信息不存在");
		}
		if(!StringUtils.equals(oldorder.getCustomerId(),customer.getId())){
			return Result.error("货源信息错误!");
		}

		hyOrderService.removeById(id);
		hyOrderSendAddressService.deleteByOrderId(id);
		hyOrderReceiveAddressService.deleteByOrderId(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
//	@AutoLog(value = "hy_order-批量删除")
//	@ApiOperation(value="hy_order-批量删除", notes="hy_order-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	@RequiresPermissions("hyorder:deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyOrderService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="hy_order-通过id查询", notes="hy_order-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		if(StringUtils.isEmpty(id)){
			return Result.error("id不能为空");
		}
		HyOrder oldorder = hyOrderService.getById(id);
		if(oldorder == null){
			return Result.error("货源信息不存在");
		}
		HyCustomer customer = null;
		if(userUtil.isSys()){
			String customerId = oldorder.getCustomerId();
			if(StringUtils.isEmpty(customerId)){
				return Result.error("货主信息不存在");
			}
			customer = userUtil.getCustomerById(customerId);
			if(customer == null){
				return Result.error("货主信息不存在");
			}
		}else {
			customer = userUtil.getCustomer();
			if(customer == null){
				return Result.error("货主信息不存在");
			}
			if("3".equals(oldorder.getOrderMode())){
				if (!StringUtils.equals(oldorder.getAgentId(), customer.getId())
						&& !StringUtils.equals(oldorder.getCustomerId(), customer.getId())
				) {
					return Result.error("货源信息错误!");
				}
			}else {
				if(!StringUtils.equals(oldorder.getCustomerId(),customer.getId())){
					return Result.error("货源信息错误!");
				}
			}
		}
		return Result.OK(oldorder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hyOrder
    */
    @RequestMapping(value = "/exportXls")
	@RequiresPermissions("hyorder:exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HyOrder hyOrder) {
    	if(!userUtil.isSys()){
			HyCustomer customer = userUtil.getCustomer();
			if(customer==null){
				throw new JeecgBootException("货主信息不存在");
			}
			hyOrder.setCustomerId("");
			// Step.1 组装查询条件
			QueryWrapper<HyOrder> queryWrapper = QueryGenerator.initQueryWrapper(hyOrder, request.getParameterMap());
			queryWrapper.eq("customer_id",customer.getId());
			return super.exportXls(queryWrapper,request, HyOrder.class, "货源");
		}
        return super.exportXls(request, hyOrder, HyOrder.class, "货源");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@RequiresPermissions("hyorder:importExcel")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HyOrder.class);
    }

	/**
	 * 通过excel导入数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/importOrder", method = RequestMethod.POST)
	@RequiresPermissions("hyorder:importExcel")
	public Result<?> importExcelOrder(HttpServletRequest request) {
		List<ImportOrderDTO> list = ExcelUtil.importExcel(request, ImportOrderDTO.class);

		if(CollectionUtils.isEmpty(list)) {
			return Result.error("导入数据不能为空！");
		}
		this.checkData(list);

		//查询货主
		List<String> customerNames = list.stream().map(
				item -> item.getCustomerName().trim()
		).distinct().filter(Objects::nonNull).collect(Collectors.toList());

		QueryWrapper queryWrapperCustomerName = new QueryWrapper();
		queryWrapperCustomerName.in("customer_name", customerNames);
		List<HyCustomer> customerNameList = customerService.list(queryWrapperCustomerName);
		if(customerNames.size() != customerNameList.size()){

			List<String>  dbCustomerNames = customerNameList.stream().map(
					item -> item.getCustomerName()
			).collect(Collectors.toList());

			String filterCustomerNames = customerNames.stream()
					.filter(item -> !dbCustomerNames.contains(item))
					.collect(Collectors.joining(",", "(", ")"));

			throw new JeecgBootException(filterCustomerNames + "货主数据信息有误");
		}
		Map <String, String> customerNameMaps  = customerNameList.stream().collect(
				Collectors.toMap(HyCustomer::getCustomerName, HyCustomer::getId, (key1, key2) -> key2)
		);

		//查询车队长
		List<String> carrierNames = new ArrayList<>();
		Map <String, HyCarrier> carrierNameMaps  = new HashMap<>();
		for(ImportOrderDTO importOrderDTO:list){
			if(StringUtils.isNotBlank(importOrderDTO.getCarrierName()) &&
					!carrierNames.contains(importOrderDTO.getCarrierName())){
				carrierNames.add(importOrderDTO.getCarrierName());
			}

		}
		if(carrierNames.size()>0){
			QueryWrapper queryWrapperCarrierName = new QueryWrapper();
			queryWrapperCarrierName.in("carrier_name", carrierNames);
			queryWrapperCarrierName.eq("iz_used", "1");
			List<HyCarrier> carrierNameList = hyCarrierService.list(queryWrapperCarrierName);

			List<String>  dbCarrierNames = carrierNameList.stream().map(
					item -> item.getCarrierName()
			).distinct().collect(Collectors.toList());

			if(carrierNames.size() != dbCarrierNames.size()){
				String filterCarrierNames = carrierNames.stream()
						.filter(item -> !dbCarrierNames.contains(item))
						.collect(Collectors.joining(",", "(", ")"));

				throw new JeecgBootException(filterCarrierNames + "车队长数据信息有误");
			}
			for(HyCarrier hyCarrier: carrierNameList){
				carrierNameMaps.put(hyCarrier.getCarrierName()+"_"+hyCarrier.getCustomerId(),hyCarrier);
			}
		}


		List<HyOrder> orders = new ArrayList <>();
		for (int j = 0; j < list.size(); j++) {
			ImportOrderDTO importOrderDTO = list.get(j);
			String customerId = customerNameMaps.get(importOrderDTO.getCustomerName());
			importOrderDTO.setCustomerId(customerId);

			if(StringUtils.isNotBlank(importOrderDTO.getCarrierName()) && carrierNameMaps.size() > 0){
				String mapkey = importOrderDTO.getCarrierName()+"_"+customerId;
				if(carrierNameMaps.get(mapkey) != null){
					HyCarrier carrier = carrierNameMaps.get(mapkey);
					importOrderDTO.setCarrierId(carrier.getId());
					importOrderDTO.setCarrierName(carrier.getCarrierName());
				}
			}

			int key =  j +2;
			HyOrder order =  hyOrderService.ImportOrderDTOTOOrder(importOrderDTO,String.valueOf(key)) ;
			orders.add(order);
		}

		hyOrderService.saveBatchOrder(orders);
		return Result.ok("文件导入成功！数据行数：" + orders.size());
	}
	private  void checkData(List<ImportOrderDTO> list){
		int i = 2;
		for(ImportOrderDTO importOrderDTO :list){
			String key = String.valueOf(i);

			if (StringUtils.isBlank(importOrderDTO.getCustomerName())) {
				throw new JeecgBootException("第"+ key+ "行  货主信息不能为空,请先补充信息");
			}
			if(StringUtils.isBlank(importOrderDTO.getPayType()) ){
				throw new JeecgBootException("第"+ key+ "行 运费支付方式不能为空");
			}

			if("2".equals(importOrderDTO.getPayType()) &&
					StringUtils.isBlank(importOrderDTO.getCarrierName())
			){
				throw new JeecgBootException("第"+ key+ "行 车队长信息不能为空,请先补充车队长信息");
			}

			i++;
		}


	}




	/**
	 * 获取wx货源二维码
	 *
	 * @param id
	 * @return
	 */
//	@AutoLog(value = "获取wx货源二维码")
	@ApiOperation(value="获取wx货源二维码", notes="获取wx货源二维码")
	@GetMapping(value = "/getWxEr")
	public Result<?> getWxEr(@RequestParam(name="id",required=true) String id) throws IOException {


		if(HyConfigUtils.getConfig().getErweimaIzUse()){
			String message= HttpURLConnectionUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+HyConfigUtils.getConfig().getErweimaAppid()+"&secret="+HyConfigUtils.getConfig().getErweimaSecret());
			Object obj= JSON.parse(message);
			String access_token="";
			if(((JSONObject) obj).get("access_token")!=null){
				 access_token=((JSONObject) obj).get("access_token").toString();
			}else{
				return Result.error("小程序appid等参数配置错误,请联系管理员");
			}
			WxQrCodeModel qrCodeModel=new WxQrCodeModel();
			qrCodeModel.setPage("pages/scan/scanjieguo");
			qrCodeModel.setScene(id);

			qrCodeModel.setPath("pages/scan/scanjieguo?msg="+id);


			//小程序码
			/*HttpResponse execute = HttpRequest.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" +access_token).body(JSON.toJSONString(qrCodeModel)).execute();
			InputStream inputStream = new ByteArrayInputStream(execute.bodyBytes());
			MultipartFile file = new MockMultipartFile( ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
			String s = uploadLocal(file);*/

			//小程序二维码
			HttpResponse execute = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" +access_token).body(JSON.toJSONString(qrCodeModel)).execute();
			InputStream inputStream = new ByteArrayInputStream(execute.bodyBytes());
			MultipartFile file = new MockMultipartFile( ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
			String s = uploadLocal(file);

		/*JSONObject paramJson = new JSONObject();
		paramJson.put("path", "pages/scan/scanjieguo?msg="+id);
		String s1 = HttpURLConnectionUtil.doPost("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" +access_token,
				paramJson.toString());*/

			return Result.OK(s);
		}else{
			return Result.error("未配置货源二维码参数,请联系管理员");
		}

	}


	/**
	 * 本地文件上传
	 * @param mf 文件
	 * @param
	 * @return
	 */
	private String uploadLocal(MultipartFile mf){
		String bizPath = "wlhy" +File.separator + DateUtils.getDate("yyyyMMdd");
		try {
			String ctxPath = uploadpath;
			String fileName = null;
			File file = new File(ctxPath + File.separator + bizPath + File.separator );
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			String orgName = mf.getOriginalFilename();// 获取文件名
			orgName = CommonUtils.getFileName(orgName);
			if(orgName.indexOf(".") != -1){
				fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
			}else{
				fileName = System.currentTimeMillis()+ "_" + orgName+".png";
			}
			String savePath = file.getPath() + File.separator + fileName;
			File savefile = new File(savePath);
			FileCopyUtils.copy(mf.getBytes(), savefile);
			String dbpath = null;
			if(oConvertUtils.isNotEmpty(bizPath)){
				dbpath = bizPath + File.separator + fileName;
			}else{
				dbpath = fileName;
			}
			if (dbpath.contains("\\")) {
				dbpath = dbpath.replace("\\", "/");
			}
			return dbpath;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}

}
